import React, { Component } from "react";
import "./uploadImg.css";
import axios from "axios";

export default class UploadImg extends Component {
  constructor(props) {
    super();
    this.state = {
      // isshow: false,
      imgUrl: ""
    };
  }
  //   componentWillReceiveProps(nextProps) {
  //     console.log(nextProps)
  //     this.setState({isshow: nextProps.data});
  //  }
  upfile(e) {
    let file = e.target.files[0];
    console.log(file);
    let param = new FormData(); // 创建form对象
    param.append("file", file); // 通过append向form对象添加数据
    let config = {
      headers: { "Content-Type": "multipart/form-data" }
    };
    axios.post("http://10.35.166.69:8888/upLoad", param, config).then(res => {
      // console.log("111");
      this.setState({
        // isshow: true,
        imgUrl: res.data.newPath
      });
      this.props.getImgUrl(res.data.newPath, true);//调用父方法，并传递参数，让父方法得到回调
    });
  }

  render() {
    return (
      <div className="upload">
        {this.props.isshow ? (
          <div className="file-ite">
            <img src={this.state.imgUrl} alt="" />
          </div>
        ) : (
          <div className="add">
            <input
              accept="image/*"
              type="file"
              id="upfile"
              onChange={e => this.upfile(e)}
            />
          </div>
        )}
      </div>
    );
  }
}
